<template>
  <el-dialog v-model="visible" :title="`${!dataForm.id ? $t('add') : $t('update')}编组信息`" :close-on-click-modal="false"
    :close-on-press-escape="false" width="720">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
      label-width="120px">
      <el-form-item :label="$t('gate.modeName')" prop="name" required>
        <el-input v-model="dataForm.name" placeholder="请输入"></el-input>
      </el-form-item>
      <div style="margin-bottom: 20px">
        <el-button @click="addTab()">
          新增规则组
        </el-button>
      </div>
      <el-tabs v-model="editableTabsValue" type="card" class="demo-tabs" closable @tab-remove="removeTab"
        @tab-change="changeTab">
        <el-tab-pane v-for="(gateRuleItem, gateRuleIndex) in dataForm.gateRuleDTOList" :key="gateRuleIndex"
          :label="`规则${gateRuleIndex + 1}`" :name="gateRuleIndex">
          <el-form-item :label="$t('device.groupId')" prop="gateRuleItem.groupId">
            <el-cascader v-model="gateRuleItem.groupId" :options="deviceGroupList" :props="groupProps" clearable />
          </el-form-item>
          <el-form-item label="是否刷卡:" prop="gateRuleItem.isCard">
            <el-radio-group v-model="gateRuleItem.isCard">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否人脸识别:" prop="gateRuleItem.isFace">
            <el-radio-group v-model="gateRuleItem.isFace">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否启动:" prop="gateRuleItem.status">
            <el-radio-group v-model="gateRuleItem.status">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="人员类型:" prop="gateRuleItem.personType">
            <el-radio-group v-model="gateRuleItem.personType">
              <el-radio :label="Number(key)" v-for="(key, index) in Object.keys(PersonTypeNames)" :key="index">{{
    PersonTypeNames[key] }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="学生类型:" prop="gateRuleItem.studentType" v-if="gateRuleItem.personType === 3">
            <el-radio-group v-model="gateRuleItem.studentType">
              <el-radio :label="Number(key)" v-for="(key, index) in Object.keys(StudentTypeNames)" :key="index">{{
    StudentTypeNames[key] }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="绑定年级:" prop="gateRuleItem.gradeId" v-if="gateRuleItem.personType === 3">
            <el-select v-model="gateRuleItem.gradeId" style="width: 200px">
              <el-option :key="item.id" :value="item.id" v-for="item in gradeList">{{item.name}}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上学时间:" prop="gateRuleItem.toSchool">
            <el-checkbox-group v-model="gateRuleItem.toSchool" @change="handleWeek($event, gateRuleIndex)">
              <el-checkbox v-for="(item, index) in weekoptions" :key="index" :label="index" :value="index">
                {{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <div style="margin-left: 30px;" v-for="(item, index) in gateRuleItem.weeks" :key="index">
            <div style="width: 50px; font-weight: bold;">{{ weekoptions[item.weekType] }}：</div>
            <div class="week-list-day-list" v-for="(s_item, s_index) in item.dayList" :key="s_index">
              <el-input style="margin: 0 10px; width: 120px" :value="`可通行时段${s_index + 1}`" readonly></el-input>
              <el-select v-model="s_item.type" style="margin: 0 10px; width: 120px">
                <el-option :key="0" value="0">进</el-option>
                <el-option :key="1" value="1">出</el-option>
              </el-select>
              <div style="width: 400px;">
                <el-time-picker is-range format="HH:mm" v-model="s_item.weekTime" value-format="HH:mm:ss"
                  range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
                </el-time-picker>
              </div>
              <el-icon :size="24" v-show="s_index === 0" @click="add(item.dayList)" style="cursor: pointer;">
                <CirclePlus />
              </el-icon>
              <el-icon :size="24" v-show="s_index > 0" @click="reMove(item.dayList, s_index)"
                style="cursor: pointer; color: #ff0046;">
                <Remove />
              </el-icon>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage, TabPaneName } from "element-plus";
import { number } from "echarts/core";
import { PersonTypeNames, StudentTypeNames } from './contant';
import { flattenTreeReduce } from "@/utils/utils";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const groupProps = {
  checkStrictly: true,
  value: 'id',
  label: 'name',
  emitPath: false,
};

const visible = ref(false);
const dataFormRef = ref();

const dataForm = reactive({
  id: "",
  name: "",
  weeks: [] as any[],
  toSchool: [],
  gateRuleDTOList: [{} as any],
});


let tabIndex = 2;
const editableTabsValue = ref(0);

const addTab = () => {
  dataForm.gateRuleDTOList.push({} as any);
  editableTabsValue.value = dataForm.gateRuleDTOList.length - 1;
};

const removeTab = (name: number) => {
  dataForm.gateRuleDTOList.splice(name, 1);
};

const changeTab = (val: any) => {
  console.log(val, editableTabsValue.value);
};

const weekoptions = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

const deviceGroupList = ref<any[]>([]);

const rules = ref({
  name: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  type: [{ required: true, message: t("validate.required"), trigger: "change" }],
  pid: [{ required: true, message: t("validate.required"), trigger: "change" }],
});

const init = (row?: any) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  Promise.all([getDeviceGroupList(), getGradeList()]).then(() => {
    if (row) {
      getInfo(row);
    }
  });
};

// 获取信息
const getInfo = (row: any) => {
  baseService.get("/gate/mode/query/rule?modeId=" + row?.id).then((res) => {
    const gateRuleDTOList = res.data.map((item: any) => {
      const newItem = Object.assign({}, item);
      newItem.weeks = item.gateTimeDTOList.map((v: any) => ({
        weekType: v.dayType,
        id: v.id,
        dayList: v.gateTimeDetailDTOList.map((v: any) => ({
          weekTime: [v.beginTime, v.endTime],
          type: String(v.type),
        }))
      }))
      newItem.toSchool = item.gateTimeDTOList.map((d: any) => d.dayType);
      return newItem;
    })
    Object.assign(dataForm, row, { gateRuleDTOList });
    console.log(dataForm);
  });
};

const add = (item: any) => {
  if (item.length >= 8) {
    ElMessage.error({
      message: '最多添加八个时段',
      duration: 500,
    });
    return;
  }
  item.push({});
};

const reMove = (item: any, index: number) => {
  item.splice(index, 1);
};

const handleWeek = (val: number[], index: number) => {
  dataForm.gateRuleDTOList[index].weeks = [];
  val.map((v: any) => {
    var obj: any = {};
    obj.weekType = v;
    obj.dayList = [{}];
    dataForm.gateRuleDTOList[index].weeks.push(obj);
  })
};

// 获取编组列表
const getDeviceGroupList = () => {
  baseService.get("/device/class/list").then((res) => {
    deviceGroupList.value = res.data;
  });
};

const gradeList = ref<any[]>([]);
// 获取年级列表
const getGradeList = () => {
  baseService.get("/data/class/list").then((res) => {
    const list = flattenTreeReduce(res.data);
    gradeList.value = list.filter((k: any) => k.type === 2);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }

    const gateRuleDTOList = dataForm.gateRuleDTOList.map((item) => {
      const newItem = Object.assign({}, item);
      newItem.gateTimeDTOList = [];
      console.log(item);
      item.weeks.map((d: any) => {
        newItem.gateTimeDTOList.push({
          dayType: d.weekType,
          gateTimeDetailDTOList: d.dayList.map((v: any) => ({
            beginTime: v.weekTime[0],
            endTime: v.weekTime[1],
            type: Number(v.type),
          }))
        })
      })
      return newItem;
    })

    const newDataForm = {
      ...dataForm,
      gateRuleDTOList,
    }


    baseService.post(`/gate/mode/${dataForm.id ? 'update' : 'addNew'}`, newDataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>

<style lang="less" scoped>
.inline {
  display: inline;
}

.week-list-day-list {
  display: flex;
  margin: 10px 0;
}
</style>
